import logging

from hostcmdtools.HostCmdTool import HostCmdTool
from sshtools.SshTool import SshTool
from tools.configmanager import config
from tools.log_custom import setup_logging

setup_logging(logging.INFO)


def setup_timezone(servers):
    print("设置时区")
    cmd = """
timedatectl set-timezone Asia/Shanghai;
hwclock -r;
hwclock -w;
"""
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_command(cmd)


def change_apt_source(servers):
    """
    适配 Ubuntu 18.04、20.04、22.04
    :return:
    """
    print("换源")
    cmd = """
. /etc/os-release && echo "$VERSION_CODENAME"
cat <<EOF > /etc/apt/sources.list
deb https://mirrors.bfsu.edu.cn/ubuntu/ $VERSION_CODENAME main restricted universe multiverse
deb https://mirrors.bfsu.edu.cn/ubuntu/ $VERSION_CODENAME-updates main restricted universe multiverse
deb https://mirrors.bfsu.edu.cn/ubuntu/ $VERSION_CODENAME-backports main restricted universe multiverse
deb https://mirrors.bfsu.edu.cn/ubuntu/ $VERSION_CODENAME-security main restricted universe multiverse
EOF
"""
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_command(cmd)


def apt_install(servers):
    """
    暂时别用！
    有些需要确认输入的包待处理。并且正常安装等待时间也很久，待拆分。
    """
    print("apt源安装软件")
    cmd = """
apt clean all;
apt update;
apt -y install atop htop iotop iftop tree telnet ncdu unzip sysstat lrzsz neofetch smartmontools build-essential gdisk;
"""
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_command(cmd)


def install_binary_pacages(servers):
    logging.info("上传 Linux二进制文件 ")
    host = HostCmdTool()
    for server in servers:
        host.rsync_upload(target_ip=server["ip"], local_dir="../packages", upload_dir="/root/", )

    cmd = """
    cd /root/packages;
    tar xvf duf_0.8.1_linux_x86_64.tar.gz;
    tar xvf dust-v0.8.6-x86_64-unknown-linux-musl.tar.gz;
    tar xvf sd-v1.0.0-x86_64-unknown-linux-musl.tar.gz;
    rm LICENSE;
    rm README.md;
    mv duf /usr/local/bin/;
    mv dust-v0.8.6-x86_64-unknown-linux-musl/dust /usr/local/bin/;
    mv sd-v1.0.0-x86_64-unknown-linux-musl/sd /usr/local/bin/;
    rm -rf dust-v0.8.6-x86_64-unknown-linux-musl;
    rm -rf sd-v1.0.0-x86_64-unknown-linux-musl;
    """
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_command(cmd)


def install_docker_deb(servers):
    logging.info("上传 docker deb 包")
    host = HostCmdTool()
    for server in servers:
        host.rsync_upload(target_ip=server["ip"], local_dir="../packages", upload_dir="/root/", )

    cmd = """
    cd /root/packages/docker-deb-bionic;
    dpkg -i ./*.deb;
    systemctl status docker.service;
    """
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_cmd_quit(cmd, "q")


def install_docker_online_script(servers):
    source = "/media/lhs/element/Linux安装包/install_docker.sh"
    host = HostCmdTool()
    for server in servers:
        host.rsync_upload(target_ip=server["ip"], local_dir=source,
                          upload_dir="/root/packages/", )
    for server in servers:
        ssh = SshTool(ssh_ip=server["ip"], ssh_user=server["user"], ssh_pwd=server["pwd"])
        ssh.run_command("cd /root/packages/;bash install_docker.sh;")


def update_docker_config(servers):
    print("修改docker配置文件")
    conf_json = """
cat <<EOF > /etc/docker/daemon.json
{
    "exec-opts": [
        "native.cgroupdriver=systemd"
    ],
    "registry-mirrors": [
        "https://docker.xuanyuan.me"
    ],
    "default-address-pools": [
        {
            "base": "192.168.200.0/24",
            "size": 24
        },
        {
            "base": "192.168.201.0/24",
            "size": 24
        },
        {
            "base": "192.168.202.0/24",
            "size": 24
        },
        {
            "base": "192.168.203.0/24",
            "size": 24
        },
        {
            "base": "192.168.204.0/24",
            "size": 24
        },
        {
            "base": "192.168.205.0/24",
            "size": 24
        }
    ],
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "1k",
        "max-file": "3"
    },
    "max-concurrent-downloads": 10
}
EOF
"""
    for server in servers:
        client = SshTool(ssh_ip=server["ip"], ssh_user=server["user"], ssh_pwd=server["pwd"])
        client.run_command(conf_json)
        cmd = """
    systemctl daemon-reload;
    systemctl restart docker;
    systemctl status docker;
        """
        client.run_cmd_quit(cmd, "q")
        client.run_command("ip -br a")


def upload_cuda(servers):
    source = "/media/lhs/element/Linux安装包/cuda_12.2.1_535.86.10_linux.run"
    host = HostCmdTool()
    for server in servers:
        host.rsync_upload(target_ip=server["ip"], local_dir=source, upload_dir="/root/packages/", )
    logging.info("已上传cuda安装包，比较耗时，请手动安装！")


def install_nvidia_container_toolkit_deb(servers):
    logging.info("上传 nvidia_container_toolkit_deb 包")
    host = HostCmdTool()
    for server in servers:
        host.rsync_upload(target_ip=server["ip"], local_dir="../packages", upload_dir="/root/", )

    cmd = """
    cd /root/packages/nvidia-container-toolkit_deb;
    dpkg -i ./*.deb;
    nvidia-ctk runtime configure --runtime=docker;
    systemctl daemon-reload;
    systemctl restart docker;
    systemctl status docker;
    """
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_command(cmd)


def config_smb(servers):
    print("配置 smb 服务")
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        cmd = """
groupadd doumo;
useradd  doumo -g doumo -s /sbin/nologin -d /dev/null;
smbpasswd -a doumo;
"""
        client.run_cmd_quit(cmd, 'abcd123$')  # 需要检查
        cmd = """
chmod -R 777 /data;
chown -R doumo:doumo /data;
chmod -R 777 /data;
"""
        client.run_command(cmd)
        cmd = """
cat <<EOF >> /etc/samba/smb.conf
[data]
comment = share folder
browseable = yes
path = /data
create mask = 0700
directory mask = 0700
valid users = doumo
force user = doumo
force group = doumo
public = yes 
available = yes 
writable = yes
EOF     
"""
        client.run_command(cmd)
        cmd = """
systemctl restart smbd.service;
"""
        client.run_command(cmd)
        client.run_command("pdbedit -L -v")


def config_rc_local(servers):
    print("配置 启动时执行的脚本")

    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        cmd = """
cat <<EOF >> /lib/systemd/system/rc-local.service
[Install]
 WantedBy=multi-user.target
EOF
"""
        client.run_command(cmd)
        cmd = """
systemctl enable rc-local.service;
touch /etc/rc.local;
chmod +x /etc/rc.local;
cat <<EOF >> /etc/rc.local
#!/bin/bash

# 启动asr
rm -f /tmp/TBNR*
cd /root/nrlj/asr
bash runAsr.sh
echo

# 启动模型main.py
cd /root/nrlj/tensorrt_api
bash start.sh
echo

# 启动翻译模型
cd /root/nrlj/setup.20240318.normal
bash start.sh
echo

exit 0

EOF
"""
        client.run_command(cmd)


def install_nfs_server(servers):
    """
    适配 Ubuntu 18.04、20.04、22.04
    :return:
    """
    print("安装nfs server")
    cmd = """
apt update;
apt -y install nfs-kernel-server;
mkdir -p /mnt/nfs_share;
chown -R nobody:nogroup /mnt/nfs_share;
chmod 777 /mnt/nfs_share;

cat <<EOF > /etc/exports
/mnt/nfs_share 10.0.2.15/24(rw,sync,no_subtree_check)
/var/nfs/general    client_ip(rw,sync,no_subtree_check)
/home               client_ip(rw,sync,no_root_squash,no_subtree_check)
# rw 表示设置目录可读写。
# sync 表示数据会同步写入到内存和硬盘中，相反 rsync 表示数据会先暂存于内存中，而非直接写入到硬盘中。
# no_root_squash NFS客户端连接服务端时如果使用的是root的话，那么对服务端分享的目录来说，也拥有root权限。
# no_all_squash 不论NFS客户端连接服务端时使用什么用户，对服务端分享的目录来说都不会拥有匿名用户权限。
EOF;
exportfs -rav;

systemctl restart nfs-kernel-server;
ufw allow from 10.0.2.15/24 to any port nfs;

showmount -e localhost;
"""
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_command(cmd)


def install_nfs_client(servers):
    """
    适配 Ubuntu 18.04、20.04、22.04
    :return:
    """
    print("安装nfs server")
    cmd = """
apt update;
apt -y install nfs-common;
mkdir -p /mnt/nfs_share;
mkdir -p /mnt/nfs_clientshare;
mount 10.0.2.15:/mnt/nfs_share /mnt/nfs_clientshare;

nano /etc/fstab;
host_ip:/var/nfs/general    /nfs/general   nfs auto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0
host_ip:/home               /nfs/home      nfs auto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0

"""
    for server in servers:
        client = SshTool(ssh_ip=server.get('ip'), ssh_user=server.get('user'), ssh_pwd=server.get('pwd'))
        client.run_command(cmd)


if __name__ == "__main__":
    nodes = config.get('ubuntu1804')
    # setup_timezone(nodes)
    # change_apt_source(nodes)
    # install_binary_pacages(nodes)
    # install_docker_deb(nodes)
    # update_docker_config(nodes)
    # upload_cuda(nodes)
    # install_nvidia_container_toolkit_deb(nodes)
    # config_rc_local(nodes)
